<template>
  <el-aside
    :width="isCollapse ? '64px' : '220px'"
    class="sidebar"
  >
    <!-- 顶部Logo/标题 + 切换按钮 -->
    <div class="sidebar-header" :class="{ collapsed: isCollapse }">
      <div class="menu-title">
        <template v-if="!isCollapse">🎓 学习系统</template>
        <!-- 收起状态下不显示任何标题内容 -->
      </div>
      <!-- 切换按钮 -->
      <div 
        class="collapse-btn" 
        @click="toggleSidebar"
        :title="isCollapse ? '展开侧边栏' : '收起侧边栏'"
      >
        <el-icon class="collapse-icon" :class="{ rotated: isCollapse }">
          <ArrowLeft />
        </el-icon>
      </div>
    </div>

    <!-- 菜单导航 -->
    <el-menu
      :default-active="activeMenu"
      :collapse="isCollapse"
      background-color="#2c3e50"
      text-color="#ecf0f1"
      active-text-color="#5dade2"
      class="menu"
      @select="handleMenuSelect"
    >
      <el-menu-item index="UserIndex">
        <el-icon><House /></el-icon>
        <span class="menu-title-text">首页</span>
      </el-menu-item>

      <el-menu-item index="user-practice">
        <el-icon><Edit /></el-icon>
        <span class="menu-title-text">我的练习</span>
      </el-menu-item>

      <el-menu-item index="user-wrong-questions">
        <el-icon><Document /></el-icon>
        <span class="menu-title-text">错题本</span>
      </el-menu-item>

      <el-menu-item index="user-favorites">
        <el-icon><Star /></el-icon>
        <span class="menu-title-text">收藏夹</span>
      </el-menu-item>

      <el-menu-item index="user-study-plan">
        <el-icon><Calendar /></el-icon>
        <span class="menu-title-text">学习计划</span>
      </el-menu-item>

      <el-menu-item index="user-exam-records">
        <el-icon><ChatDotRound /></el-icon>
        <span class="menu-title-text">考试记录</span>
      </el-menu-item>

      <el-menu-item index="user-discussion">
        <el-icon><Message /></el-icon>
        <span class="menu-title-text">社区讨论</span>
      </el-menu-item>

      <el-menu-item index="user-profile">
        <el-icon><User /></el-icon>
        <span class="menu-title-text">个人中心</span>
      </el-menu-item>
    </el-menu>

    <!-- 底部用户信息（可选） -->
    <div class="sidebar-footer" :class="{ collapsed: isCollapse }">
      <div class="user-info" @mouseenter="showLogout = true" @mouseleave="showLogout = false">
        <el-icon class="user-avatar"><Avatar /></el-icon>
        <span v-if="!isCollapse" class="username">张同学</span>
        
        <!-- 退出登录按钮 -->
        <div 
          v-if="showLogout" 
          class="logout-btn"
          @click="handleLogout"
          :title="'退出登录'"
        >
          <el-icon><SwitchButton /></el-icon>
          <span v-if="!isCollapse">退出</span>
        </div>
      </div>
    </div>
  </el-aside>
</template>

<script>
import {
  House,
  Edit,
  Document,
  Star,
  Calendar,
  ChatDotRound,
  Message,
  User,
  ArrowLeft,
  Avatar,
  SwitchButton
} from '@element-plus/icons-vue'

export default {
  name: 'UserSidebar',
  props: {
    activeMenu: {
      type: String,
      required: true
    }
  },
  emits: ['update:activeMenu'],
  data() {
    return {
      isCollapse: false, // 默认展开状态
      showLogout: false // 控制退出登录按钮的显示
    }
  },
  created() {
    // 组件创建时从本地存储读取用户偏好设置
    this.loadSidebarState()
  },
  methods: {
    /**
     * 切换侧边栏展开/收起状态
     * 这个方法不仅改变视觉状态，还会保存用户的偏好设置
     */
    toggleSidebar() {
      this.isCollapse = !this.isCollapse
      // 保存用户偏好到本地存储
      this.saveSidebarState()
      
      // 可选：触发一个全局事件，让父组件知道侧边栏状态变化
      // 这样可以让主内容区域做相应的布局调整
      this.$emit('sidebar-toggle', this.isCollapse)
    },

    /**
     * 保存侧边栏状态到本地存储
     * 使用localStorage确保用户下次访问时保持相同的设置
     */
    saveSidebarState() {
      try {
        localStorage.setItem('sidebar-collapsed', JSON.stringify(this.isCollapse))
      } catch (error) {
        console.warn('无法保存侧边栏状态到本地存储:', error)
      }
    },

    /**
     * 从本地存储加载侧边栏状态
     * 如果用户之前设置过偏好，就使用保存的设置，否则使用默认展开状态
     */
    loadSidebarState() {
      try {
        const savedState = localStorage.getItem('sidebar-collapsed')
        if (savedState !== null) {
          this.isCollapse = JSON.parse(savedState)
        }
      } catch (error) {
        console.warn('无法从本地存储读取侧边栏状态:', error)
        // 如果读取失败，保持默认状态（展开）
        this.isCollapse = false
      }
    },

    /**
     * 处理退出登录操作
     * 清除本地存储的用户登录信息并跳转到登录页面
     */
    handleLogout() {
      try {
        // 清除登录相关的本地存储信息
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        
        // 可选：清除其他用户相关的缓存数据
        // localStorage.removeItem('sidebar-collapsed') // 如果希望保持侧边栏偏好，可以注释这行
        
        // 跳转到登录页面
        this.$router.push({ path: '/login' })
        
        // 可选：显示退出成功的提示信息
        this.$message.success('已安全退出登录')
      } catch (error) {
        console.error('退出登录时发生错误:', error)
        // 即使出错也要尝试跳转到登录页面
        this.$router.push({ path: '/login' })
      }
    },
    handleMenuSelect(key) {
      this.$emit('update:activeMenu', key)
      this.$router.push({ name: key })
    }
  },
  components: {
    House,
    Edit,
    Document,
    Star,
    Calendar,
    ChatDotRound,
    Message,
    User,
    ArrowLeft,
    Avatar,
    SwitchButton
  }
}
</script>

<style scoped>
.sidebar {
  background-color: #2c3e50;
  transition: width 0.3s ease;
  overflow: hidden;
  height: 100vh;
  position: relative;
}

/* 侧边栏头部样式 */
.sidebar-header {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  border-bottom: 1px solid #34495e;
  position: relative;
}

.sidebar-header.collapsed {
  justify-content: center;
  padding: 0 12px;
}

.menu-title {
  font-size: 18px;
  font-weight: bold;
  color: #ecf0f1;
  transition: all 0.3s ease;
  overflow: hidden;
  white-space: nowrap;
}

/* 切换按钮样式 */
.collapse-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 6px;
  background-color: rgba(93, 173, 226, 0.2);
  transition: all 0.3s ease;
}

.collapse-btn:hover {
  background-color: rgba(93, 173, 226, 0.3);
  transform: scale(1.05);
}

.collapse-icon {
  color: #5dade2;
  font-size: 16px;
  transition: transform 0.3s ease;
}

/* 当侧边栏收起时，箭头旋转180度 */
.collapse-icon.rotated {
  transform: rotate(180deg);
}

.menu-title-text {
  display: inline-block;
  margin-left: 10px;
  white-space: nowrap;
  overflow: hidden;
  transition: all 0.3s ease;
}

.el-menu--collapse .menu-title-text {
  margin-left: 0;
  max-width: 0;
  opacity: 0;
}

.menu {
  border-right: none;
  flex: 1;
}

/* 侧边栏底部用户信息样式 */
.sidebar-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background-color: #34495e;
  border-top: 1px solid #3d566e;
  display: flex;
  align-items: center;
  padding: 0 16px;
  transition: all 0.3s ease;
}

.sidebar-footer.collapsed {
  justify-content: center;
  padding: 0 12px;
}

.user-info {
  display: flex;
  align-items: center;
  color: #ecf0f1;
  width: 100%;
  position: relative;
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.user-info:hover {
  background-color: rgba(93, 173, 226, 0.1);
}

.user-avatar {
  font-size: 24px;
  margin-right: 12px;
  color: #5dade2;
  flex-shrink: 0;
}

.username {
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.sidebar-footer.collapsed .username {
  display: none;
}

/* 退出登录按钮样式 */
.logout-btn {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  gap: 4px;
  background-color: #e74c3c;
  color: #fff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 10;
}

.logout-btn:hover {
  background-color: #c0392b;
  transform: translateY(-50%) scale(1.05);
}

/* 收起状态下的退出按钮样式调整 */
.sidebar-footer.collapsed .logout-btn {
  right: 50%;
  transform: translate(50%, -50%);
  padding: 6px;
}

.sidebar-footer.collapsed .logout-btn span {
  display: none;
}

/* 为菜单项添加更好的悬停效果 */
.el-menu-item:hover {
  background-color: rgba(93, 173, 226, 0.15) !important;
}

/* 激活状态的菜单项样式优化 */
.el-menu-item.is-active {
  background-color: rgba(129, 193, 236, 0.25) !important;
  border-right: 3px solid #5dade2;
}
</style>